<template>
  <!-- 添加修改对话框 -->
  <el-dialog
    v-model="isShow"
    :title="`${title}用户`"
    width="700"
  >
      <FormList 
        ref="formRef"
        :formData="form"
        :formConfig="formConfig"
      ></FormList>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelHandle">取消</el-button>
        <el-button type="primary" @click="saveHandle">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="user">
import { ref, reactive, toRaw, computed } from "vue";
import { Search, Plus, Delete, Edit, Upload, Pointer } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import { useMessage } from "@/hooks/message";
import {getUserListApi,  addUserApi, updateUserApi, delUserApi, getRoleOptionApi, getSexOptionApi} from '@/api/user';
import FormList from './FormList.vue';

const props = defineProps(['sexOptions', 'roleOptions'])
const emit = defineEmits(['search'])

const message = useMessage();
const formRef = ref(null)
const isShow = ref(false);
let title = ref('');

let form = reactive({
  username: "",
  password: '',
  phone: '',
  age: "",
  sex: "",
  role: "",
  photo: 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2025%2F0225%2F55e11aebj00ss7wp00032d000sg00sgg.jpg&thumbnail=660x2147483647&quality=80&type=jpg',
  createdAt: "",
  updatedAt: "",
});

const formConfig = computed(() => {
  return {
    inline: false,
    labelWidth: '120px',
    rules: {
      username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
      ],
      password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
      ],
      phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { required: true, pattern : /^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: ['blur', 'change'] },
      ],
      role: [
        { required: true, message: '角色不能为空', trigger: ['blur', 'change'] },
      ],
    },
    itemList: [
      {type: 'input', label: '用户名', prop: 'username', placeholder: '请输入', clearable: true,},
      {type: 'input', label: '密码', prop: 'password', placeholder: '请输入'},
      {type: 'input', label: '手机号', prop: 'phone', placeholder: '请输入'},
      {type: 'input', label: '年龄', prop: 'age',  placeholder: '请输入', rules: [], clearable: true,},
      {type: 'select', label: '性别', prop: 'sex', placeholder: '请输入', 
        option: props.sexOptions
      },
      {type: 'select', label: '角色', prop: 'role', placeholder: '请输入', 
        optionLabel: 'label', optionValue: 'id', option: props.roleOptions,
      },
      {type: 'textarea', label: '头像', prop: 'photo',  placeholder: '请输入', rules: [], clearable: true,},
      {type: 'date', label: '创建日期', prop: 'createdAt',  placeholder: '请选择',},
      {type: 'date', label: '修改日期', prop: 'updatedAt',  placeholder: '请选择',},
    ]
  }
})


const show = (option = {}) => {
  console.log(option);
  
  isShow.value = true;
  title.value = option.title;
  option.form && (form = option.form)
}

const cancelHandle = () => {
  // formRef.value.formRef.resetFields()
  formRef.value.resetFields()
  isShow.value = false;
};

const saveHandle = async() => {
  // formRef.value.validateP().then(res => {
  //   console.log(888, res);
  // }).catch(err => {
  //   console.log(55, err);
  // })
  // return

  
  // await formRef.value.formRef.validate((valid, fields) => {
  await formRef.value.validate((valid, fields) => {

    if (valid) {
      let addOrUpdate;
      if (title.value == '新增') {
        addOrUpdate = addUserApi
        delete form.userid
        delete form._id
      } else {
        addOrUpdate = updateUserApi
      }
      
      addOrUpdate(form).then(res => {
        if (res.code == 200) {
          cancelHandle();
          emit('search')
          message.success(res.msg)
        }else {
          // message.error(res.msg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
};

defineExpose({
  show,
})
</script>

<style lang="less" scoped>
  .el-input {
    --el-input-width: 500px;
  }

  .el-select {
    --el-select-width: 500px;
  }

  .el-textarea {
    width: 500px;
  }
</style>
